import os,subprocess
from src.globle import *
import time

def system_info():
    run_sudo_command("su")
    #cpu型号
    # my_cpu = os.popen("grep -m1 'model name' /proc/cpuinfo | awk -F: '{print $2}'").read().strip()     
    my_cpu = subprocess.check_output(["grep", "-m1", "model name", "/proc/cpuinfo"]).decode().strip().split(":")[1].strip()
    # 系统版本
    # version = os.popen("cat /etc/os-release | grep -w 'VERSION' | awk -F'=' '{print $2}'").read().strip()
    version = subprocess.check_output(["grep", "-w", "VERSION", "/etc/os-release"]).decode().strip().split("=")[1]
    # 小版本号
    # version_small = os.popen("cat /etc/kylin-build | grep -w 'Build' | awk -F' ' '{print $2}'").read().strip()
    version_small = subprocess.check_output(["grep", "-w", "Build", "/etc/kylin-build"]).decode().strip().split()[1]
    # 服务序列号
    # kylin_serial = os.popen("kylin_serial").read().strip() 
    kylin_serial = subprocess.check_output(["sudo", "kylin_serial"]).decode().strip()
    # 激活码
    # kyactivation_key = os.popen("cat /etc/.kyactivation 2>/dev/null").read().strip()
    kyactivation_key=None
    if os.path.exists("/etc/.kyactivation"):
        kyactivation_key = subprocess.check_output(["cat", "/etc/.kyactivation"], stderr=subprocess.DEVNULL).decode().strip()
    # 注册码
    # kyregistration_key = os.popen("kylin_gen_register").read().strip()
    kyregistration_key = subprocess.check_output(["sudo", "kylin_gen_register"]).decode().strip()
    # 主机序列号
    # system_serial_number = os.popen("cat /sys/class/dmi/id/product_serial").read().strip()
    system_serial_number = subprocess.check_output(["sudo", "cat", "/sys/class/dmi/id/product_serial"]).decode().strip() 
    # 硬盘序列号
    # blk_serials = os.popen("lsblk -d -o NAME,SERIAL,TYPE -P | grep disk").read().strip() 
    blk_serials = subprocess.check_output(["lsblk", "-d", "-o", "NAME,SERIAL,TYPE", "-P"]).decode().strip()
    # 网卡地址
    # phy_adapters = [phy_adapter for phy_adapter in os.listdir('/sys/class/net/') if phy_adapter not in os.listdir('/sys/devices/virtual/net/')]  
    # for phy_adapter in phy_adapters:
    #     mac = os.popen(f"cat /sys/class/net/{phy_adapter}/address").read().strip()
    phy_adapters = [phy_adapter for phy_adapter in os.listdir('/sys/class/net/') if phy_adapter not in os.listdir('/sys/devices/virtual/net/')]
    for phy_adapter in phy_adapters:
        mac = subprocess.check_output(["cat", f"/sys/class/net/{phy_adapter}/address"]).decode().strip()
    print_head(head=[
        ".......................请等待10秒左右.........................."
    ])
    print_options(options={
        "CPU型号为": my_cpu,
        "操作系统版本为": version,
        "操作系统小版本号为": version_small,
        "服务序列号为": kylin_serial,
        "激活码为": kyactivation_key,
        "注册码": kyregistration_key,
        "主机序列号": system_serial_number,
        "硬盘序列号": blk_serials,
        "网卡名": phy_adapters,
        "网卡MAC地址为": mac
    })
    get_pause()

def net_speed():
    duration = int(input("\n请输入测试时长（秒）："))
    print("--- In ------ Out ---")
    start_time = time.time()
    while time.time() - start_time <= duration:
        with open('/proc/net/dev', 'r') as f:
            for line in f:
                if active_interface in line:
                    fields = line.strip().split()
                    old_in, old_out = int(fields[1]), int(fields[9])
                    break
        time.sleep(1)
        with open('/proc/net/dev', 'r') as f:
            for line in f:
                if active_interface in line:
                    fields = line.strip().split()
                    new_in, new_out = int(fields[1]), int(fields[9])
                    break
        in_speed = (new_in - old_in) / 1024 / 1024 * 8
        out_speed = (new_out - old_out) / 1024 / 1024 * 8
        print(f"{in_speed:.2f} Mbps {out_speed:.2f} Mbps")
    get_pause()

def backup_log():
    run_sudo_command("su")
    time_stamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    subprocess.run(["sudo", "tar", "-czvPf", f"/home/{local_user}/桌面/log_{time_stamp}.tar.gz", "/var/log"])
    subprocess.run(["sudo", "chmod", "777", f"/home/{local_user}/桌面/log_{time_stamp}.tar.gz"])

    print(f"找到log_{time_stamp}.tar.gz这个文件，备份到桌面了，从桌面拷出来发给我\n")
    get_pause()


import subprocess
from datetime import datetime

def sys_operation_info():
    run_sudo_command("su")
    if os.path.exists(f"/home/{local_user}/桌面"):
        file_path = f"/home/{local_user}/桌面/stat_cpu_mem.txt"
    else:
        if os.path.exists(f"/home/{local_user}"):
            file_path = f"/home/{local_user}/stat_cpu_mem.txt"
        else:
            file_path = "/home/stat_cpu_mem.txt"

    with open(file_path, "a") as f:
        ps_cpu = subprocess.run(["ps", "aux", "--sort=-%cpu"], capture_output=True, text=True).stdout[:11]
        ps_mem = subprocess.run(["ps", "aux", "--sort=-%mem"], capture_output=True, text=True).stdout[:11]
        free_mem = subprocess.run(["free", "-h"], capture_output=True, text=True).stdout
        interrupts = subprocess.run(["cat", "/proc/interrupts"], capture_output=True, text=True).stdout

        f.write(f"""{datetime.now()}
            占用cpu最高的10个进程是:
            {ps_cpu}
            占用mem最高的10个进程是:
            {ps_mem}
            总体内存使用情况是:
            {free_mem}
            中断情况是:
            {interrupts}
        """)

        print_options(options={
            "占用cpu最高的10个进程是:": ps_cpu,
            "占用mem最高的10个进程是:": ps_mem,
            "总体内存使用情况是:": free_mem,
            "中断情况是:": interrupts
        })
    get_pause()

def system_messages():
    print_head(head=[
        ".......................系统相关信息.........................."
    ])
    print_menu_options(menu_options=[
        "查询系统信息",
        "查看实时网速",
        "备份日志到桌面",
        "查看系统运行信息"
    ])
    select_menu(menu_dict={
        '0': return_to_previous_menu,
        '1': system_info,
        '2': net_speed,
        '3': backup_log,
        '4': sys_operation_info
    })
